package com.js.nickcar.api;

import android.content.Context;
import android.text.TextUtils;

import com.js.nickcar.MyApplication;
import com.js.nickcar.entity.remote.LoginBean;
import com.zyzd.commontools.cache.SpUtil;

import java.util.Date;

/**
 * Created by 李宗源 on 2017/2/10.
 */

public class UserHelper {
    /**
     * 客户端类型：1：用户；2：咨询师
     */
    public static final String type = "driver";
    private static LoginBean loginBean;
    private static String token;
    private static String userId;

    /**
     * @return 时间戳:使用13位
     */
    public static long getTimeStamp() {
        return (new Date()).getTime();
    }

    /**
     * 获取token,当返回值为null时需要跳转登录界面
     *
     * @return
     */
    public static String getToken() {
        if (TextUtils.isEmpty(token)) {
            token = SpUtil.CACHE.getString(SpConfig.TOKEN, "");
        }

        if (TextUtils.isEmpty(token)) {
            return "";
        }

        return token;
    }

    /**
     * 获取userid
     *
     * @return
     */
    public static String getUserId() {
        if (TextUtils.isEmpty(userId)) {
            userId = SpUtil.CACHE.getString(SpConfig.USER_ID, "");
        }
        return userId;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public static LoginBean getLoginInfo() {
        if (loginBean == null) {
            loginBean = SpUtil.CACHE.getObject(SpConfig.USER_INFO, LoginBean.class);
        }
        return loginBean;
    }

    /**
     * 更新token,设置为""即为清空token
     *
     * @param newToken
     */
    public static void updateToken(String newToken) {
        token = newToken;
        SpUtil.CACHE.putString(SpConfig.TOKEN, newToken);
    }

    /**
     * 更新userId,设置为""即为清空用户信息
     *
     * @param newUserId
     */
    public static void updateUserId(String newUserId) {
        userId = newUserId;
        SpUtil.CACHE.putString(SpConfig.USER_ID, newUserId);
    }

    /**
     * 更新用户信息
     *
     * @param newLoginInfo
     */
    public static void updateUserInfo(LoginBean newLoginInfo) {
        loginBean = newLoginInfo;
        if (newLoginInfo != null) {
            UserObserver.notifyPersonInfoChanged();
        }
        SpUtil.CACHE.putObject(SpConfig.USER_INFO, loginBean);
    }


    /**
     * 退出账号
     */
    public static void exit() {
        updateUserId(null);
        updateToken(null);
        updateUserInfo(null);
    }


    private static Context getContext() {
        return MyApplication.getContext();
    }

    public static boolean isUnLogin() {
        return TextUtils.isEmpty(getToken()) || TextUtils.isEmpty(getUserId());
    }

}
